import React, {Component} from 'react'
import {View, Alert, AsyncStorage} from 'react-native'
import Storage from 'react-native-storage'
import Toast from 'react-native-root-toast'
import {connect} from 'react-redux'
import AppNavigation from './configs/navigation'
import Login from './components/users/login'

//初始化数据库
let storage = new Storage({
  // 最大容量，默认值1000条数据循环存储
  size: 1000,

  // 存储引擎：对于RN使用AsyncStorage，对于web使用window.localStorage
  // 如果不指定则数据只会保存在内存中，重启后即丢失
  storageBackend: AsyncStorage,

  // 数据过期时间(秒)，设为null则永不过期
  defaultExpires: null,

  // 读写时在内存中缓存数据。默认启用
  enableCache: true,

});

global.storage = storage;
global.Toast = Toast;
global.loginState = {}
global.App = {
  host: 'http://oa.xiayuanyin.cn',
};


class Initializer extends Component {
  constructor(props) {
    super(props)
    // 关联到外部
    App.logout = (msg) => {
      loginState = {}
      storage.remove({key: 'loginState'})
      this.setState({login: false})
      Alert.alert(msg || '退出登录成功')
    }
    App.refreshLogin = (school_id)=>{
      this.props.dispatch({type: 'reload', school_id})
      // this.setState({login: false}, ()=>{this.setState({login: true, school_id: school_id})})
    }
    this.state = {login: loginState.user_id!=null, school_id: ''}
  }

  componentWillReceiveProps () {
    this.forceUpdate()
  }

  componentDidMount() {
    storage.load({key: 'loginState'}).then(res => {
      Object.assign(loginState, res)
      this.setLogin(res.school_id)
    }).catch(e => this.state = {})
  }

  setLogin = (school_id) => {
    this.setState({login: true, school_id: school_id})
  }

  render() {
    if(this.state.login)
      return <AppNavigation schoolId={this.props.user.school_id}/>
    else
      return <Login successCallback={this.setLogin}/>
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
};

export default connect(mapStateToProps)(Initializer)